// 购物车
// 作者：洪刚

const express = require("express")
const db = require("../model/db")
const router = express.Router();

// 添加商品到购物车
router.post("/add", async (req, res) => {
    const data = await db.Shopping.create(req.body);
    res.send(true);
})

// 得到所有
router.get("/all", async (req, res) => {
    let connection = {};  //条件对象
    if (req.query.key) {
        const exp = new RegExp(req.query.key, "i")//不区分大小写，模糊查询正则表达式
        connection = {
            $or: [
                { name: { $regex: exp } },   //购物车中的商品名字
            ]
        }
    }
    const data = await db.Shopping.find(connection);
    const count = await db.Shopping.countDocuments(connection);
    res.send({
        code: 0,
        msg: "",
        count: count,
        data: data
    });
});

// 修改
router.put("/:id", async (req, res) => {
    await db.Shopping.updateOne({
        _id: req.params.id
    }, req.body);
    res.send(true);
})

// 删除
router.delete("/:id", async (req, res) => {
    await db.Shopping.deleteOne({
        _id: req.params.id
    })
    res.send(true);
})


module.exports = router;